package com.shop.zkmall.app.im;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.shop.zkmall.app.common.CacheConstants;
import com.shop.zkmall.app.domain.res.JoinGroupResult;
import com.shop.zkmall.app.domain.res.ProductInfo;
import com.shop.zkmall.app.im.core.Result;
import com.shop.zkmall.app.im.core.properties.TxImProperties;
import com.shop.zkmall.app.redis.service.api.impl.RedisService;
import com.shop.zkmall.app.utils.JsonUtils;
import com.shop.zkmall.app.utils.RedisUtils;
import com.tencentyun.TLSSigAPIv2;
import lombok.SneakyThrows;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
@Component
public class TxImTemplate implements TxTemplate {

    @Autowired
    private RedisService redisService;

    //参考文档 https://blog.csdn.net/Java_Mr_Jin/article/details/126870142

    private final static Logger log = LoggerFactory.getLogger(TxImTemplate.class);

    private static final String OK = "OK";

    private static final String APP_MANAGER = "administrator";

    private static final String HTTPS_URL_PREFIX = "https://console.tim.qq.com/";
    private TxImProperties txImProperties;


    @SneakyThrows(Exception.class)
    public TxImTemplate(TxImProperties properties) {
        this.txImProperties = properties;
    }


//    public boolean isFriend(String userId1, String userId2) {
//        try {
//            Integer random = new Random().nextInt(Integer.MAX_VALUE);
//
//            String url = getHttpsUrl("v4/sns/friend_check", random);
//
//            // 请求参数
//            JSONObject body = new JSONObject();
//            body.put("CheckType", "CheckResult_Type_Both");
//            body.put("From_Account", userId1);
//            body.put("To_Account", Arrays.asList(userId2));
//
//            // 发送请求
//            String response = HttpUtil.post(url, body.toString());
//
//            JSONObject json = JSONUtil.parseObj(response);
//
//            // 判断返回是否成功
//            String actionStatus = json.getString("ActionStatus");
//            if (!"OK".equalsIgnoreCase(actionStatus)) {
//                log.error("好友检查失败: {}", json.toStringPretty());
//                return false;
//            }
//
//            JSONArray array = json.getJSONArray("InfoItem");
//            if (array == null || array.isEmpty()) {
//                return false;
//            }
//
//            JSONObject info = array.getJSONObject(0);
//            String relation = info.getStr("Relation");
//
//            return "CheckResult_Type_Both".equals(relation);
//
//        } catch (Exception e) {
//            log.error("查询好友关系异常:", e);
//            return false;
//        }
//    }




    /**
     * 获取腾讯im请求路径
     */
    private String getHttpsUrl(String pathApi, Integer random) {
        return String.format("%s%s?sdkappid=%s&identifier=%s&usersig=%s&random=%s&contenttype=json",
            HTTPS_URL_PREFIX, pathApi, txImProperties.getSdkAppId(), APP_MANAGER, this.getUserSign(), random);
    }


    @Override
    public String getUserSign() {
        String key = CacheConstants.TX_USER_SIGN;
        Object sign = redisService.getCacheObject(key);
        if (sign == null) {
            TLSSigAPIv2 tlsSigAPIv2 = new TLSSigAPIv2(txImProperties.getSdkAppId(), txImProperties.getSdkSecretKey());
            String userSign = tlsSigAPIv2.genUserSig(APP_MANAGER, 60 * 86400);
            redisService.setCacheObject(key, userSign, 60 * 86400L, TimeUnit.SECONDS);
            return userSign;
        }
        return sign.toString();
    }

    @Override
    public String getUserSign(String userId) {
        TLSSigAPIv2 tlsSigAPIv2 = new TLSSigAPIv2(txImProperties.getSdkAppId(), txImProperties.getSdkSecretKey());
        String userSign = tlsSigAPIv2.genUserSig(userId, 60 * 86400);
        return userSign;
    }

    /**
     * 创建账号
     * @param userId 腾讯用户ID
     * @param userName 腾讯名称
     * @param faceUrl  头像
     */
    @Override
    public Boolean accountImport(String userId, String userName, String faceUrl) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentImApiConstant.AccountManage.ACCOUNT_IMPORT, random);
        HashMap<String, Object> map = new HashMap<>();
        map.put("UserID", userId);
        if (StringUtils.isNotEmpty(userName)) {
            map.put("Nick", userName);
        }
        if (StringUtils.isNotEmpty(faceUrl)) {
            map.put("FaceUrl", faceUrl);
        }
        log.info("腾讯云im导入单个账号，请求参数：{}", map);
        try {
            String result = HttpUtil.post(httpsUrl, JsonUtils.toJsonString(map));
            log.info("腾讯云im导入单个账号，返回结果：{}", result);
            Result resultEntity = JSONUtil.toBean(result, Result.class);
            return resultEntity.getActionStatus().equals(OK) && resultEntity.getErrorCode() == 0;
        }catch (Exception e){
            log.info("腾讯云im导入单个账号，报错结果：{}", e.getMessage());
        }
        return false;
    }

    /**
     * 创建账号
     * @param userId 腾讯用户ID
     * @param userName 腾讯名称
     * @param faceUrl  头像
     */
    @Override
    public Boolean updateUserInfo(String userId, String userName, String faceUrl) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentImApiConstant.PortraitManage.PORTRAIT_SET, random);
        HashMap<String, Object> map = new HashMap<>();
        ArrayList<Object> list = new ArrayList<>();
        map.put("From_Account", userId);
        if (StringUtils.isNotBlank(userName)) {
            HashMap<String, Object> name = new HashMap<>();
            name.put("Tag", "Tag_Profile_IM_Nick");
            name.put("Value", userName);
            list.add(name);
        }
        if (StringUtils.isNotBlank(faceUrl)) {
            HashMap<String, Object> image = new HashMap<>();
            image.put("Tag", "Tag_Profile_IM_Image");
            image.put("Value", faceUrl);
            list.add(image);
        }
        map.put("ProfileItem", list);
        if(list.isEmpty()){
            return false;
        }
        log.info("腾讯云im修改用户资料，请求参数：{}", map);
        try {
            String result = HttpUtil.post(httpsUrl, JsonUtils.toJsonString(map));
            log.info("腾讯云im修改用户资料，返回结果：{}", result);
            Result resultEntity = JSONUtil.toBean(result, Result.class);
            return resultEntity.getActionStatus().equals(OK) && resultEntity.getErrorCode() == 0;
        }catch (Exception e){
            log.info("腾讯云im修改用户资料，报错结果：{}", e.getMessage());
        }
        return false;
    }

    @Override
    public String createGroup(String name, String userId, String notification, List<String> meberList,String image) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentImApiConstant.GroupManage.CREATE_GROUP, random);
        HashMap<String, Object> map = new HashMap<>();
        map.put("Owner_Account", userId);
        map.put("Type", "Public");
        map.put("Name", name);
        map.put("ApplyJoinOption", "FreeAccess");
        map.put("InviteJoinOption", "FreeAccess");
        if (StringUtils.isNotBlank(notification)) {
            map.put("Notification", notification);
        }
        if (StringUtils.isNotBlank(image)) {
            map.put("FaceUrl", image);
        }
        ArrayList<Object> members = new ArrayList<>();
        meberList.forEach(e->{
            HashMap<String, Object> member = new HashMap<>();
            member.put("Member_Account", e);
            members.add(member);
        });
        map.put("MemberList",members);
        log.info("腾讯云im创建群组，请求参数：{}", map);
        try {
            String result = HttpUtil.post(httpsUrl, JsonUtils.toJsonString(map));
            log.info("腾讯云im创建群组，返回结果：{}", result);
            Result resultEntity = JSONUtil.toBean(result, Result.class);
            if(resultEntity.getActionStatus().equals(OK) && resultEntity.getErrorCode() == 0){
                return resultEntity.getGroupId();
            }
        }catch (Exception e){
            log.info("腾讯云im创建群组，报错结果：{}", e.getMessage());
        }
        return null;
    }

    @Override
    public String createLiveGroup(String name, String owner, String notification, String image) {

        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentImApiConstant.GroupManage.CREATE_GROUP, random);

        HashMap<String, Object> map = new HashMap<>();
        map.put("Owner_Account", owner);
        map.put("Type", "AVChatRoom");
        map.put("Name", name);
        map.put("ApplyJoinOption", "FreeAccess");

        if (StringUtils.isNotBlank(notification)) {
            map.put("Notification", notification);
        }
        if (StringUtils.isNotBlank(image)) {
            map.put("FaceUrl", image);
        }

        log.info("IM 创建直播群，请求参数：{}", map);

        try {
            String result = HttpUtil.post(httpsUrl, JsonUtils.toJsonString(map));
            log.info("IM 创建直播群，返回结果：{}", result);

            Result resultEntity = JSONUtil.toBean(result, Result.class);
            if ("OK".equals(resultEntity.getActionStatus()) && resultEntity.getErrorCode() == 0) {
                return resultEntity.getGroupId();
            }
        } catch (Exception e) {
            log.error("IM 创建直播群异常：{}", e.getMessage());
        }
        return null;
    }



    public void addAdminToLiveGroup(String groupId, String adminId) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String url = getHttpsUrl("group_open_http_svc/add_group_member", random);

        HashMap<String, Object> map = new HashMap<>();
        map.put("GroupId", groupId);

        List<Object> members = new ArrayList<>();
        HashMap<String, Object> admin = new HashMap<>();
        admin.put("Member_Account", adminId);
        admin.put("Role", "Admin");
        members.add(admin);

        map.put("MemberList", members);

        HttpUtil.post(url, JsonUtils.toJsonString(map));
    }




    /**
     * 需改群组信息
     * @param groupId 群组ID
     * @param name 群组名称
     * @param faceUrl 群组头像
     * @param notification 群组公告
     * @param muteAllMember  设置全员禁言（选填）:"On"开启，"Off"关闭
     * @param applyJoinOption  申请加群方式（选填）
     * @param inviteJoinOption 邀请加群处理方式(选填)
     * @return
     */
    @Override
    public Boolean updateGroup(String groupId, String name, String faceUrl, String notification, String muteAllMember, String applyJoinOption, String inviteJoinOption) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentImApiConstant.GroupManage.CREATE_GROUP, random);
        HashMap<String, Object> map = new HashMap<>();
        map.put("GroupId", groupId);
        if (StringUtils.isNotBlank(name)) {
            map.put("Name", name);
        }
        if (StringUtils.isNotBlank(faceUrl)) {
            map.put("FaceUrl", faceUrl);
        }
        if (StringUtils.isNotBlank(notification)) {
            map.put("Notification", notification);
        }
        if (StringUtils.isNotBlank(muteAllMember)) {
            map.put("MuteAllMember", muteAllMember);
        }
        if (StringUtils.isNotBlank(applyJoinOption)) {
            map.put("ApplyJoinOption", applyJoinOption);
        }
        if (StringUtils.isNotBlank(inviteJoinOption)) {
            map.put("InviteJoinOption", inviteJoinOption);
        }
        log.info("腾讯云im修改群组资料，请求参数：{}", map);
        try {
            String result = HttpUtil.post(httpsUrl, JsonUtils.toJsonString(map));
            log.info("腾讯云im修改群组资料，返回结果：{}", result);
            Result resultEntity = JSONUtil.toBean(result, Result.class);
            return resultEntity.getActionStatus().equals(OK) && resultEntity.getErrorCode() == 0;
        }catch (Exception e){
            log.info("腾讯云im修改群组资料，报错结果：{}", e.getMessage());
        }
        return false;


    }

    @Override
    public Boolean insertUserGroup(String groupId, List<String> meberList) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentImApiConstant.GroupManage.ADD_GROUP_MEMBER, random);
        HashMap<String, Object> map = new HashMap<>();
        map.put("GroupId", groupId);
        ArrayList<Object> list = new ArrayList<>();
        meberList.forEach(e->{
            HashMap<String, Object> user = new HashMap<>();
            user.put("Member_Account",e);
            list.add(user);
        });
        map.put("MemberList", list);
        try {
            log.info("腾讯云im增加群组成员，请求参数：{}", map);
            String result = HttpUtil.post(httpsUrl, JsonUtils.toJsonString(map));
            log.info("腾讯云im增加群组成员，返回结果：{}", result);
            Result resultEntity =JSONUtil.toBean(result, Result.class);
            return resultEntity.getActionStatus().equals(OK) && resultEntity.getErrorCode() == 0;
        }catch (Exception e){
            log.info("腾讯云im增加群组成员，报错结果：{}", e.getMessage());
        }
        return false;
    }

    @Override
    public Boolean removeUserGroup(String groupId, List<String> meberList) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentImApiConstant.GroupManage.DELETE_GROUP_MEMBER, random);
        HashMap<String, Object> map = new HashMap<>();
        map.put("GroupId", groupId);
        map.put("MemberToDel_Account", meberList);
        try {
            String result = HttpUtil.post(httpsUrl, JsonUtils.toJsonString(map));
            log.info("腾讯云im删除群组成员，返回结果：{}", result);
            Result resultEntity = JSONUtil.toBean(result, Result.class);
            return resultEntity.getActionStatus().equals(OK) && resultEntity.getErrorCode() == 0;
        }catch (Exception e){
            log.info("腾讯云im删除群组成员，报错结果：{}", e.getMessage());
        }
        return false;
    }

    /**
     * 修改群组成员资料
     * @param map 修改的群成员资料
     * @return
     */
    @Override
    public Boolean updateUserGroup(Map<String, String> map) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentImApiConstant.GroupManage.MODIFY_GROUP_MEMBER_INFO, random);
        try {
            String result = HttpUtil.post(httpsUrl, JsonUtils.toJsonString(map));
            log.info("腾讯云im修改群成员资料，返回结果：{}", result);
            Result resultEntity = JSONUtil.toBean(result, Result.class);
            return resultEntity.getActionStatus().equals(OK) && resultEntity.getErrorCode() == 0;
        }catch (Exception e){
            log.info("腾讯云im修改群成员资料，报错结果：{}", e.getMessage());
        }
        return null;
    }

    /**
     * 转让群主
     * @param groupId 群组ID
     * @param userId 腾讯的用户ID
     * @return
     */
    @Override
    public Boolean updateManagerGroup(String groupId, String userId) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentImApiConstant.GroupManage.CHANGE_GROUP_OWNER, random);
        HashMap<String, Object> map = new HashMap<>();
        map.put("GroupId", groupId);
        map.put("NewOwner_Account", userId);
        try {
            String result = HttpUtil.post(httpsUrl, JsonUtils.toJsonString(map));
            log.info("腾讯云IM转让群主，返回结果：{}", result);
            Result resultEntity = JSONUtil.toBean(result, Result.class);
            return resultEntity.getActionStatus().equals(OK) && resultEntity.getErrorCode() == 0;
        }catch (Exception e){
            log.info("腾讯云IM转让群主，报错结果：{}", e.getMessage());
        }
        return false;
    }

    @Override
    public Boolean forbidUserGroup(String groupId, List<String> userIdList, Integer time) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentImApiConstant.GroupManage.FORBID_SEND_MSG, random);

        HashMap<String, Object> map = new HashMap<>();
        map.put("GroupId", groupId);
        map.put("MuteTime", time);

        // ⭐ 如果是全体禁言，不要传 Members_Account
        if (userIdList != null && !userIdList.isEmpty()) {
            map.put("Members_Account", userIdList);
        }

        try {
            String result = HttpUtil.post(httpsUrl, JsonUtils.toJsonString(map));
            log.info("腾讯云IM禁言响应：{}", result);
            Result resultEntity = JSONUtil.toBean(result, Result.class);
            return "OK".equals(resultEntity.getActionStatus()) && resultEntity.getErrorCode() == 0;
        } catch (Exception e){
            log.error("腾讯云IM禁言失败：{}", e.getMessage());
        }
        return false;
    }

    /**
     * 解除全体禁言（全体允许发言）
     */
    public Boolean unForbidAllUser(String groupId) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentImApiConstant.GroupManage.FORBID_SEND_MSG, random);

        HashMap<String, Object> map = new HashMap<>();
        map.put("GroupId", groupId);
        map.put("MuteTime", 0); // ⭐ 0 = 解除禁言
        // ⭐ 不要传 Members_Account，代表操作全体成员

        try {
            String result = HttpUtil.post(httpsUrl, JsonUtils.toJsonString(map));
            log.info("腾讯云IM解除全体禁言响应：{}", result);
            Result resultEntity = JSONUtil.toBean(result, Result.class);
            return "OK".equals(resultEntity.getActionStatus()) && resultEntity.getErrorCode() == 0;
        } catch (Exception e) {
            log.error("腾讯云IM解除全体禁言失败：{}", e.getMessage());
        }
        return false;
    }



    @Override
    public Boolean removeGroupAdmin(String groupId, List<String> userIdList) {
        Integer random = RandomUtils.nextInt(0, 999999999);

        String httpsUrl = getHttpsUrl(TencentImApiConstant.GroupManage.MODIFY_GROUP_MEMBER_INFO, random);

        try {
            for (String userId : userIdList) {
                HashMap<String, Object> map = new HashMap<>();
                map.put("GroupId", groupId);
                map.put("Member_Account", userId);
                map.put("Role", "Member"); // ⭐ 关键：恢复普通成员

                String result = HttpUtil.post(httpsUrl, JsonUtils.toJsonString(map));
                log.info("腾讯云IM取消群管理员，成员 {} ，返回结果：{}", userId, result);

                Result resultEntity = JSONUtil.toBean(result, Result.class);
                if (!"OK".equals(resultEntity.getActionStatus()) || resultEntity.getErrorCode() != 0) {
                    // 只要有一个失败就算整个失败
                    return false;
                }
            }
        } catch (Exception e) {
            log.error("腾讯云IM取消群管理员失败：{}", e.getMessage());
            return false;
        }

        return true;
    }



    /**
     * 销毁群组
     * @param groupId 群组ID
     * @return
     */
    @Override
    public Boolean destroyGroup(String groupId) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentImApiConstant.GroupManage.DESTROY_GROUP, random);
        HashMap<String, Object> map = new HashMap<>();
        map.put("GroupId", groupId);
        try {
            String result = HttpUtil.post(httpsUrl, JsonUtils.toJsonString(map));
            log.info("腾讯云IM解散群组，返回结果：{}", result);
            Result resultEntity = JSONUtil.toBean(result, Result.class);
            return resultEntity.getActionStatus().equals(OK) && resultEntity.getErrorCode() == 0;
        }catch (Exception e){
            log.info("腾讯云IM解散群组，报错结果：{}", e.getMessage());
        }
        return null;
    }

    /**
     * 删除账号
     * @param userIds 用户id集合
     */
    public void accountDelete(List<String> userIds) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentImApiConstant.AccountManage.ACCOUNT_DELETE, random);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("DeleteItem", getUserIdJsonList(userIds));
        log.info("腾讯云im删除账号，请求参数：{}", jsonObject);
        String result = HttpUtil.post(httpsUrl, jsonObject.toString());
        log.info("腾讯云im删除账户，返回结果：{}", result);
    }


    /**
     * 查询账号是否已经导入im
     * @param userIds 用户id集合
     */
    public String accountCheck(List<String> userIds) {
        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentImApiConstant.AccountManage.ACCOUNT_CHECK, random);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("CheckItem", getUserIdJsonList(userIds));
        log.info("腾讯云im查询账号，请求参数：{}", jsonObject);
        String result = HttpUtil.post(httpsUrl, jsonObject.toString());
        log.info("腾讯云im查询账号，返回结果：{}", result);
        return result;
    }


    private List<JSONObject> getUserIdJsonList(List<String> userIds) {
        return userIds.stream().map(v -> {
            JSONObject userIdJson = new JSONObject();
            userIdJson.put("UserID", v);
            return userIdJson;
        }).collect(Collectors.toList());
    }


    /**
     * 添加好友
     * @param userId        发起加好友的用户ID
     * @param friendUserId  被添加的好友用户ID
     */
    public void addFriend(String userId, String friendUserId) {
        if (StrUtil.isEmpty(userId) || StrUtil.isEmpty(friendUserId)) {
            log.error("addFriend 参数错误：userId 或 friendUserId 为空");
            return;
        }

        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentImApiConstant.RelationManage.FRIEND_ADD, random);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("From_Account", userId);

        JSONArray addFriendItem = new JSONArray();
        Map<String, String> map = new HashMap<>();
        map.put("To_Account", friendUserId);
        map.put("AddSource", "AddSource_Type_AdminAdd");
        map.put("AddWording", "我们成为好友吧~");
        addFriendItem.add(map);

        jsonObject.put("AddFriendItem", addFriendItem);

        log.info("腾讯云IM添加好友，请求参数：{}", jsonObject.toString());
        String result = HttpUtil.post(httpsUrl, jsonObject.toString());
        log.info("腾讯云IM添加好友，返回结果：{}", result);
    }

    @Override
    public Boolean addGroupAdmin(String groupId, List<String> userIdList) {
        Integer random = RandomUtils.nextInt(0, 999999999);

        String httpsUrl = getHttpsUrl(TencentImApiConstant.GroupManage.MODIFY_GROUP_MEMBER_INFO, random);

        try {
            for (String userId : userIdList) {
                HashMap<String, Object> map = new HashMap<>();
                map.put("GroupId", groupId);
                map.put("Member_Account", userId);
                map.put("Role", "Admin"); // ⭐ 关键：设置为管理员

                String result = HttpUtil.post(httpsUrl, JsonUtils.toJsonString(map));
                log.info("腾讯云IM添加群管理员，成员 {} ，返回结果：{}", userId, result);

                Result resultEntity = JSONUtil.toBean(result, Result.class);
                if (!"OK".equals(resultEntity.getActionStatus()) || resultEntity.getErrorCode() != 0) {
                    // 只要有一个失败就全部失败
                    return false;
                }
            }
        } catch (Exception e) {
            log.error("腾讯云IM添加群管理员失败：{}", e.getMessage());
            return false;
        }

        return true;
    }


    @Override
    public boolean joinLiveGroup(String groupId, String userId) {

        Integer random = RandomUtils.nextInt(0, 999999999);
        String httpsUrl = getHttpsUrl(TencentImApiConstant.GroupManage.JOIN_GROUP, random);

        Map<String, Object> map = new HashMap<>();
        map.put("GroupId", groupId);
        map.put("Member_Account", userId);

        log.info("腾讯云IM加入直播群，请求参数：{}", map);

        try {
            String result = HttpUtil.post(httpsUrl, JsonUtils.toJsonString(map));
            log.info("腾讯云IM加入直播群，返回结果：{}", result);

            JoinGroupResult resultEntity = JSONUtil.toBean(result, JoinGroupResult.class);

            // 正常加入成功
            if ("OK".equals(resultEntity.getActionStatus()) && resultEntity.getErrorCode() == 0) {
                return true;
            }

            // 特殊情况：AVChatRoom 已经在群里了，也算成功
            if (resultEntity.getErrorCode() == 10013) {
                log.info("用户已在直播群内，无需重复加入");
                return true;
            }

            log.warn("加入直播群失败：{}", resultEntity.getErrorInfo());
        } catch (Exception e) {
            log.error("加入直播群异常：{}", e.getMessage());
        }

        return false;
    }



    public boolean pushProductToLiveRoom(String groupId, ProductInfo product) {

        Integer random = RandomUtils.nextInt(0, 999999999);
        String url = getHttpsUrl("v4/group_open_http_svc/send_group_system_notification", random);

        Map<String, Object> body = new HashMap<>();
        body.put("GroupId", groupId);
        body.put("Content", JsonUtils.toJsonString(product)); //推送商品数据

        log.info("推送商品到直播间，请求参数：{}", body);

        try {
            String res = HttpUtil.post(url, JsonUtils.toJsonString(body));
            log.info("推送商品到直播间，返回结果：{}", res);

            Result result = JSONUtil.toBean(res, Result.class);
            return "OK".equals(result.getActionStatus());
        } catch (Exception e) {
            log.error("推送商品异常：{}", e.getMessage());
            return false;
        }
    }



}
